package com.frame.project.modules.test.sys.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.frame.project.modules.test.sys.dao.SysPermissionDao;
import com.frame.project.modules.test.sys.dao.SysRoleDao;
import com.frame.project.modules.test.sys.dao.SysUserDao;
import com.frame.project.modules.test.sys.entity.SysPermission;
import com.frame.project.modules.test.sys.entity.SysRole;
import com.frame.project.modules.test.sys.entity.SysUser;
import com.github.pagehelper.PageInfo;

/**
 * @author Administrator
 *
 */
@Service
public class SysUserService {

	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysRoleDao sysRoleDao;
	
	@Autowired
	private SysPermissionDao sysPermissionDao;

	
	public PageInfo<SysUser> findList(){
		List<SysUser> userDomains = sysUserDao.findUserList();
		PageInfo<SysUser> result = new PageInfo<SysUser>(userDomains);
		return result;
	}


	/**
	 * 用户登录逻辑
	 * @param sysUser
	 * @return
	 */
	public SysUser getUser(SysUser sysUser){
		SysUser user = sysUserDao.getUser(sysUser);
		//查角色名称
		if (user != null) {
			List<SysRole> sysRoleList = sysRoleDao.findUserRoleList(user);
			List<String> roles = new ArrayList<>();
			Set<String> permissions = new HashSet<>();
			user.setSysRole(sysRoleList);
			String roleNames = "";
			if(sysRoleList != null) {
				for (SysRole sysRole : sysRoleList) {
					roleNames += sysRole.getName()+",";
					roles.add(sysRole.getName());
					//查权限
					List<SysPermission> findRolePermissionList = sysPermissionDao.findRolePermissionList(sysRole);
					for (SysPermission sysPermission : findRolePermissionList) {
						permissions.add(sysPermission.getName());
					}
				}
				roleNames = roleNames.substring(0, roleNames.length()-1);//截取最后一个
				user.setRoleNames(roleNames);
				user.setRoles(roles);
				user.setSysPermission(permissions);
			}
		}
		return user;
	}

	public int count(){
		return sysUserDao.count();
	}

}
